using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Voodoo.Sauce.Debugger;

namespace Voodoo.Sauce.Internal.DebugScreen
{
	public class DebugIssueNumberBadge : MonoBehaviour
	{
		[SerializeField]
		private Text numberText;

		[SerializeField]
		private bool hideIfEmpty;

		[SerializeField]
		private GameObject badgeObject;

		private int _issuesCount;

		private void Awake()
		{
			LogConsoleDebugScreen.Closed = (Action)Delegate.Combine(LogConsoleDebugScreen.Closed, new Action(RefreshCounts));
			RefreshCounts();
		}

		private void OnDestroy()
		{
			LogConsoleDebugScreen.Closed = (Action)Delegate.Remove(LogConsoleDebugScreen.Closed, new Action(RefreshCounts));
		}

		private void OnEnable()
		{
			LogsTracker.OnLogReceived += LogsTrackerOnIssueMessageReceived;
			RefreshCounts();
		}

		private void OnDisable()
		{
			LogsTracker.OnLogReceived -= LogsTrackerOnIssueMessageReceived;
		}

		private void RefreshCounts()
		{
			_issuesCount = 0;
			IReadOnlyCollection<LogMessage> issues = LogsTracker.Issues;
			if (issues == null)
			{
				numberText.text = "???";
			}
			else
			{
				foreach (LogMessage item in issues)
				{
					if (MustIssueBeCounted(item))
					{
						_issuesCount++;
					}
				}
				numberText.text = $"{_issuesCount}";
			}
			badgeObject.SetActive(!hideIfEmpty || _issuesCount > 0);
		}

		private void LogsTrackerOnIssueMessageReceived(LogMessage issueMessage)
		{
			if (MustIssueBeCounted(issueMessage))
			{
				_issuesCount++;
				numberText.text = $"{_issuesCount}";
				badgeObject.SetActive(value: true);
			}
		}

		private static bool MustIssueBeCounted(LogMessage issueMessage)
		{
			if (DebugLogTypes.IsEnabled(issueMessage.logType))
			{
				return LogConsoleDebugScreen.MessageMatchesSearchText(issueMessage);
			}
			return false;
		}
	}
}
